/*
 * @Author: your name
 * @Date: 2021-05-17 10:48:53
 * @LastEditTime: 2021-05-18 10:40:16
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /vite-project/src/store/modules/permission.ts
 */
import type { AppRouteRecordRaw, Menu } from '@/router/types';
import { toRaw } from 'vue';
import { defineStore } from 'pinia';
import { store } from '@/store';
import { useUserStore } from './user';
import { flatMultiLevelRoutes } from '@/router/helper/routeHelper';
import projectSetting from '@/settings/projectSetting';
import { PermissionModeEnum } from '@/enums/appEnum';
import { filter } from '@/utils/helper/treeHelper';
import { asyncRoutes } from '@/router/routes';

interface PermissionState {
    menuList: Menu[],
    // 是否动态添加路由
    isDynamicAddedRoute: boolean;
}

export const usePermissionStore = defineStore({
    id: 'app-permission',
    state: (): PermissionState => ({
        menuList: [],
        isDynamicAddedRoute: false
    }),
    getters: {
        getMenuList(): Menu[] {
            return this.menuList;
        },
        getIsDynamicAddedRoute(): boolean {
            return this.isDynamicAddedRoute;
        },
    },
    actions: {
        setMenuList(list: Menu[]) {
            this.menuList = list;
        },
        setDynamicAddedRoute(added: boolean) {
            this.isDynamicAddedRoute = added;
        },
        async buildRoutesAction(id?: number | string): Promise<AppRouteRecordRaw[]> {
            
            const userStore = useUserStore();

            let routes: AppRouteRecordRaw[]  = [];
            const roleList = toRaw(userStore.getRoleList);
            // 页面权限模式
            const permissionMode = projectSetting.permissionMode;

            if (permissionMode == PermissionModeEnum.ROLE) {
                const routeFilter = (route: AppRouteRecordRaw) => {
                    const {meta} = route;
                    const {roles} = meta || {};
                    if (!roles) return true;
                    return roleList.some((role) => roles.includes(role));
                }
                routes = filter(asyncRoutes, routeFilter);
                routes = routes.filter(routeFilter);
                routes = flatMultiLevelRoutes(routes);
            }
            return routes;
        }
    }
});

export function usePermissionStoreWidthOut() {
  return usePermissionStore(store);
}